package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.dto.PrivateChatDto;
import com.kang.entity.ChatRecord;
import com.kang.entity.ChatRecordNum;
import com.kang.entity.SysUser;
import com.kang.entity.UserRelevancy;
import com.kang.mapper.ChatRecordMapper;
import com.kang.mapper.ChatRecordNumMapper;
import com.kang.mapper.LoginMapper;
import com.kang.mapper.UseRelevancyMapper;
import com.kang.service.UseRelevancyService;
import com.kang.util.ThreadLocalUtil;
import com.kang.vo.ChatUserIdVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class UseRelevancyServiceImpl extends ServiceImpl<UseRelevancyMapper, UserRelevancy> implements UseRelevancyService {

    @Autowired
    private UseRelevancyMapper useRelevancyMapper;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    private ChatRecordMapper chatRecordMapper;

    @Autowired
    private ChatRecordNumMapper chatRecordNumMapper;

    @Override
    public Map<String,Object> getPrivateChat(Integer id) {
        List<PrivateChatDto> resultList = new ArrayList<>();
        //当前用户联系过的其他用户
        QueryWrapper<UserRelevancy> wrapper = new QueryWrapper<>();
        wrapper.eq("login_user_id",id);
        wrapper.last("order by update_time desc");
        List<UserRelevancy> selectList = useRelevancyMapper.selectList(wrapper);
        //私聊过的表用户id信息
        List<Integer> releateUserList = selectList.stream().map(UserRelevancy::getRelevancyUserId).collect(Collectors.toList());
        //查询私聊过的用户信息
        QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.in("id",releateUserList);
        List<SysUser> userList = loginMapper.selectList(userQueryWrapper);
        for (SysUser sysUser : userList) {
            PrivateChatDto privateChatDto = new PrivateChatDto();
            privateChatDto.setId(sysUser.getId());
            privateChatDto.setUsername(sysUser.getUsername());
            privateChatDto.setHeadUrl(sysUser.getHeadUrl());
            //查询数据库  当前联系过人的id 找最新消息和最新时间
            ChatRecord chatRecord = chatRecordMapper.fingChatRecord(id, sysUser.getId());
            privateChatDto.setHeadMessage(Objects.isNull(chatRecord) ? null : chatRecord.getContext());
            privateChatDto.setNewDate(Objects.isNull(chatRecord) ? null : chatRecord.getUpdateTime());
            // 未读消息数量   注意是当前用户接收别人发的信息
            Integer count = chatRecordNumMapper.fingChatRecordNum(sysUser.getId(),id);
            privateChatDto.setUnreadNum(count);
            resultList.add(privateChatDto);
        }
        QueryWrapper<SysUser> sysUserQueryWrapper = new QueryWrapper<>();
        sysUserQueryWrapper.eq("id",id);
        SysUser sysUser = loginMapper.selectOne(sysUserQueryWrapper);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("resultList",resultList);
        resultMap.put("username",sysUser.getUsername());
        resultMap.put("headUrl",sysUser.getHeadUrl());

        return resultMap;
    }

    @Override
    public Page<ChatRecord> getChatRecorde(ChatUserIdVo vo) {
        //点击聊天页面后未读消息表中数据情况
        chatRecordNumMapper.deleteChatRecordNum(vo.getReceiveUserId(),vo.getSendUserId());
        Page<ChatRecord> page = new Page<>(vo.getCurrent(),vo.getPageSize());
        return chatRecordMapper.fingChatRecordList(page,vo.getSendUserId(),vo.getReceiveUserId());
    }

    @Override
    public boolean deleteChatUser(ChatUserIdVo vo) {
        //删除聊天记录'
        QueryWrapper<ChatRecord> wrapperOne = new QueryWrapper<>();
        wrapperOne.eq("send_user_id",vo.getSendUserId()).eq("recive_user_id",vo.getReceiveUserId());
        chatRecordMapper.delete(wrapperOne);
        //删除聊天列表
        QueryWrapper<UserRelevancy> wrapperThree = new QueryWrapper<>();
        wrapperThree.eq("login_user_id",vo.getSendUserId()).eq("relevancy_user_id",vo.getReceiveUserId());
        useRelevancyMapper.delete(wrapperThree);
        //删除未读信息
        QueryWrapper<ChatRecordNum> wrapperTwo = new QueryWrapper<>();
        wrapperTwo.eq("send_user_id",vo.getSendUserId()).eq("recive_user_id",vo.getReceiveUserId());
        chatRecordNumMapper.delete(wrapperTwo);
        return true;
    }

    @Override
    public Integer insertUserRelevancy(Integer userId) {
        Integer id = ThreadLocalUtil.getCurrentUser().getId();
        QueryWrapper<UserRelevancy> wrapper = new QueryWrapper<>();
        wrapper.eq("login_user_id",id).eq("relevancy_user_id",userId);
        Integer count = useRelevancyMapper.selectCount(wrapper);
        if (count == 0) {
            //当前用户
            UserRelevancy userRelevancy = new UserRelevancy();
            userRelevancy.setLoginUserId(id);
            userRelevancy.setRelevancyUserId(userId);
            userRelevancy.setCreateTime(new Date());
            userRelevancy.setUpdateTime(new Date());
            useRelevancyMapper.insert(userRelevancy);
            UserRelevancy relevancy = new UserRelevancy();
            relevancy.setLoginUserId(userId);
            relevancy.setRelevancyUserId(id);
            relevancy.setCreateTime(new Date());
            relevancy.setUpdateTime(new Date());
            useRelevancyMapper.insert(relevancy);
        }
        return 1;
    }
}
